package com.example.book_libapp;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.database.library.BookFunctions;
import com.example.database.library.DatabaseHandler;

public class Booksearchresults extends Activity {

	static final String TAG_BOOKS = "books";
	static final String TAG_BOOK = "book";
	static final String TAG_ID = "id";
	static final String TAG_TITLE = "title";
	static final String TAG_INFO = "introduction";
	static final String TAG_COVER = "cover";
	static final String TAG_PAGE = "page";
	static final String TAG_PERPAGE = "perpage";
	static final String TAG_TOTAL = "total";
	static final String TAG_PAGES = "pages";
	static final String TAG_STAT = "stat";
	static final String TAG_KEY = "query";
	static final String TAG_SORT = "sort_type";
	static final String TAG_CAT = "category";
	ArrayList<HashMap<String, String>> contactList;
	HashMap<String, String> map;

	JSONObject json;

	JSONObject jsonbook;
	// contacts JSONArray
	JSONArray contacts = null;
	ListView list;
	BookListAdapter adapter;
	String search_key;
	String sort;
	String category;
	boolean endpage = false;
	int pagecount;

	public void onSearch(View v) {
		onSearchRequested();
	}

	public void onHome(View v) {
		return2Home(this);
	}

	public void return2Home(Context context) {
		final Intent intent = new Intent(context, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		context.startActivity(intent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.book_resultlistview);

		
		// get intent data
		Intent intent = getIntent();
		search_key = intent.getStringExtra(TAG_KEY);
		sort = intent.getStringExtra(TAG_SORT);
		category = intent.getStringExtra(TAG_CAT);
		
		
		Log.e("sEARCH KEY", "" + search_key);
				
		pagecount = 1;
		list = (ListView) findViewById(R.id.listV_main);
		View footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.listfooter, null, false);
		list.addFooterView(footerView);

		contactList = new ArrayList<HashMap<String, String>>();

		BookFunctions BookFunction = new BookFunctions();
		json = BookFunction.BookDetailSearch(search_key, "", "", "", "", Integer.toString(pagecount), "20");
//		json = BookFunction.BookMainSearch(search_key, pagecount, "20");
		
		// bestseller, page, count)(pagecount);

		try {
			Log.e("JSON",
					"aldaa --------------------------------------------------"
							+ json.toString() + " ");
			if (json.getString(TAG_STAT).toString().equals("ok")) {

				jsonbook = json.getJSONObject(TAG_BOOKS);

				Log.e("JSON",
						"aldaa --------------------------------------------------"
								+ json.getString(TAG_STAT).toString() + " "
								+ jsonbook.getString(TAG_PERPAGE) + " "
								+ jsonbook.getString(TAG_PAGES));

				DatabaseHandler db = new DatabaseHandler(
						getApplicationContext());
				// db.resetBookListInfoTables();
				// db.addBooklistinfo(jsonbook.getString(TAG_PAGE),
				// jsonbook.getString(TAG_PERPAGE),jsonbook.getString(TAG_TOTAL),jsonbook.getString(TAG_PAGES));
				// db.addBooklistinfo("asdf","asdfasdf","asfasdf","asfasdf");
				contacts = jsonbook.getJSONArray(TAG_BOOK);
				if (Integer.parseInt(jsonbook.getString(TAG_PAGE)) == Integer
						.parseInt(jsonbook.getString(TAG_PAGES))) {
					endpage = true;
				}
				for (int i = 0; i < contacts.length(); i++) {
					JSONObject c = contacts.getJSONObject(i);
					String id = c.getString(TAG_ID);
					String title = c.getString(TAG_TITLE);
					String brief = c.getString(TAG_INFO);
					String cover = c.getString(TAG_COVER);

					// creating new HashMap
					map = new HashMap<String, String>();

					// adding each child node to HashMap key => value
					map.put(TAG_ID, id);
					map.put(TAG_TITLE, title);
					map.put(TAG_INFO, brief);
					map.put(TAG_COVER, cover);

					// adding HashList to ArrayList
					contactList.add(map);
				}
			} else {
				Toast msg = Toast.makeText(getApplicationContext(),
						"Ном олдсонгүй", Toast.LENGTH_LONG);
				msg.show();
				endpage = true;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// Getting adapter by passing xml data ArrayList
		adapter = new BookListAdapter(this, contactList);
		list.setAdapter(adapter);

		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {

				String book_id = ((TextView) v.findViewById(R.id.book_id))
						.getText().toString();
				Log.e("ERROR", "--------------------" + book_id + " --");
				Intent i = new Intent(getApplicationContext(),
						BookDetails.class);
				i.putExtra(TAG_ID, book_id);
				startActivity(i);

			}
		});

		list.setOnScrollListener(new OnScrollListener() {

			// useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			// dumdumdum
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				// what is the bottom iten that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;

				// is the bottom item visible & not loading more already ? Load
				// more !
				if ((lastInScreen == totalItemCount) && endpage == false) {
					Log.v("Scroll Event",
							"Scroll Event Scroll Event Scroll Event");
					new loadMoreListView().execute();
				}
			}
		});

	}

	private class loadMoreListView extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {

		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {

					pagecount++;
					BookFunctions BookFunction = new BookFunctions();
					json = BookFunction.BookDetailSearch(search_key, "", "", "", "", Integer.toString(pagecount), "20");
					try {
						// Log.e("JSON",
						// "aldaa --------------------------------------------------"
						// + json.getString(TAG_STAT).toString() + " "+
						// json.getString(TAG_PERPAGE));
						if (json.getString(TAG_STAT).toString().equals("ok")) {

							jsonbook = json.getJSONObject(TAG_BOOKS);

							if (Integer.parseInt(jsonbook.getString(TAG_PAGE)) == Integer
									.parseInt(jsonbook.getString(TAG_PAGES))) {
								endpage = true;
								Log.e("loadingMore",
										"loadingMore doInBackground --------------------------------------------------");
							}

							Log.e("JSON",
									"aldaa --------------------------------------------------"
											+ json.getString(TAG_STAT)
													.toString() + " "
											+ jsonbook.getString(TAG_PAGE)
											+ "<>"
											+ jsonbook.getString(TAG_PAGES));

							// DatabaseHandler db = new
							// DatabaseHandler(getApplicationContext());
							// db.resetBookListInfoTables();
							// db.addBooklistinfo(jsonbook.getString(TAG_PAGE),
							// jsonbook.getString(TAG_PERPAGE),jsonbook.getString(TAG_TOTAL),jsonbook.getString(TAG_PAGES));
							// db.addBooklistinfo("asdf","asdfasdf","asfasdf","asfasdf");
							contacts = jsonbook.getJSONArray(TAG_BOOK);

							for (int i = 0; i < contacts.length(); i++) {
								JSONObject c = contacts.getJSONObject(i);
								String id = c.getString(TAG_ID);
								String title = c.getString(TAG_TITLE);
								String brief = c.getString(TAG_INFO);
								String cover = c.getString(TAG_COVER);

								Log.e("Book", " " + id + " " + " " + title
										+ " " + brief + " " + cover);
								// // creating new HashMap
								HashMap<String, String> map = new HashMap<String, String>();

								// adding each child node to HashMap key =>
								// value
								map.put(TAG_ID, id);
								map.put(TAG_TITLE, title);
								map.put(TAG_INFO, brief);
								map.put(TAG_COVER, cover);

								// adding HashList to ArrayList
								contactList.add(map);
							}
						} else {
							Toast msg = Toast.makeText(getApplicationContext(),
									"Ном олсонгүй.", Toast.LENGTH_LONG);
							msg.show();
							endpage = true;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

					int currentPosition = list.getFirstVisiblePosition();

					// Getting adapter by passing xml data ArrayList
					adapter = new BookListAdapter(Booksearchresults.this,
							contactList);
					list.setAdapter(adapter);

					list.setSelectionFromTop(currentPosition + 1, 0);
				}
			});

			return (null);
		}

		protected void onPostExecute(Void unused) {

		}
	}
}